#coding=utf-8
#!/usr/bin/python

'''
Created on 2012-11-17

@author: Neo.Chen
'''

'''
功能：定时检查冒泡客的数据，存放数据库，提供查询接口，如果数据比前一天少很多，就报警通知
'''

import time
import sys
import logging
import http.client
import json
import sqlite3
from ktlib import ktlib
from ktlib import kttlv
from ktlib import sky

#获取检查的频率
def get_check_inteval():
    return 3600

def getAppName():
    return "keapp_monitor"

g_lastDate = ""
def getLastDate():
    #使用全局变量
    global g_lastDate
    return g_lastDate

def setLastDate(newDate):
    #使用全局变量
    global g_lastDate
    g_lastDate = newDate

def DoSkyMonitorError(message):
    sky.SendErrorMessage(getAppName(), message)

def connDB():
    if sys.platform != 'win32':
        dbName = "/home/cheng/py/mopo.db"
    else:
        dbName = "c:\\mopo.db"
    conn = sqlite3.connect(dbName)
    return conn

def createTable(conn):
    sql = "create table mopo_info(id integer primary key, appid integer, \
        day_key varchar(20), daliy_open_user integer, daliy_paid_money integer, \
        update_time varchar(30), time_t integer)"
    ktlib.create_sqlite_table(conn, "mopo_info", sql)

#保存数据
def saveInfo(appid, day_key, daliy_open_user, daliy_paid_money):
    #创建以及写入
    conn = connDB()
    createTable(conn)
    cn = conn.cursor()

    now = time.asctime()
    time_t = time.time()
    #主键不指定，可以自动增长
    sql = "insert into mopo_info(id, appid, day_key, daliy_open_user, daliy_paid_money, update_time, time_t) \
        values(null, %d, '%s', %d, %d, '%s', %d)" % (appid, day_key, daliy_open_user, daliy_paid_money, now, time_t)
    cn.execute(sql)
    conn.commit()
    cn.close()
    return

#查询数据
def queryInfo(day_key):
    conn = connDB()
    createTable(conn)
    cn = conn.cursor()

    daliy_open_user = 0
    daliy_paid_money = 0
    sql = "select daliy_open_user, daliy_paid_money from mopo_info where day_key='%s' order by id desc limit 1" % (day_key)
    cn.execute(sql)
    query = cn.fetchall()
    print(query)
    for line in query:
        print(line)                     #得到一维列表 (1,)
        daliy_open_user = line[0]       #表是否已经存在
        daliy_paid_money = line[1]       #表是否已经存在
    cn.close()
    return (daliy_open_user, daliy_paid_money)


#查询数据
def queryInfoByTime(time_begin, time_end):
    conn = connDB()
    createTable(conn)
    cn = conn.cursor()

    daliy_open_user = 0
    daliy_paid_money = 0
    sql = "select daliy_open_user, daliy_paid_money from mopo_info where time_t>%d and time_t<=%d order by id desc limit 1" % (time_begin,time_end)
    cn.execute(sql)
    query = cn.fetchall()
    print(query)
    for line in query:
        print(line)                     #得到一维列表 (1,)
        daliy_open_user = line[0]       #表是否已经存在
        daliy_paid_money = line[1]       #表是否已经存在
    cn.close()
    return (daliy_open_user, daliy_paid_money)

#分析数据
def analysisInfo(appid, day_key, daliy_open_user, daliy_paid_money):
    '''
    nowDate = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    #判断是否跨天，不是跨天，则返回
    if getLastDate() == nowDate:
        return

    yesterday = time.strftime('%Y-%m-%d',time.localtime(time.time()-3600*24))
    beforeyesterday = time.strftime('%Y-%m-%d',time.localtime(time.time()-3600*24*2))
    #根据昨天记录和前天的记录，得到数值比例，如果相差20%则发邮件报警
    (daliy_open_user2, daliy_paid_money2) = queryInfo(yesterday)
    (daliy_open_user1, daliy_paid_money1) = queryInfo(beforeyesterday)

    logging.info("analysisInfo, yesterday:%s, beforeyesterday:%s" % (yesterday, beforeyesterday))
    logging.info("analysisInfo, daliy_open_user1:%d, daliy_paid_money1:%d" % (daliy_open_user1, daliy_paid_money1))
    logging.info("analysisInfo, daliy_open_user2:%d, daliy_paid_money2:%d" % (daliy_open_user2, daliy_paid_money2))

    if daliy_open_user1 > 0:
        userRate = (daliy_open_user2 - daliy_open_user1) * 100 / daliy_open_user1
        moneyRate = (daliy_paid_money2 - daliy_paid_money1) * 100 / daliy_paid_money1
        if userRate < -10 or moneyRate < -10:
            sky.SendErrorMessage(getAppName(), "userRate:%d, moneyRate:%d" % (userRate, moneyRate))
            logging.warning("analysisInfo, userRate:%d, moneyRate:%d" % (userRate, moneyRate))
        else:
            logging.info("analysisInfo, ok")
    setLastDate(nowDate)
    '''
    time_t = time.time()
    time_begin1 = time_t-3600*24*1-3600     #昨天
    time_end1 = time_t-3600*24*1            #昨天
    time_begin2 = time_t-3600               #今天
    time_end2 = time_t                      #今天

    (daliy_open_user1, daliy_paid_money1) = queryInfoByTime(time_begin1, time_end1)
    (daliy_open_user2, daliy_paid_money2) = queryInfoByTime(time_begin2, time_end2)

    logging.info("analysisInfo, time_begin1:%d, time_end1:%d" % (time_begin1, time_end1))
    logging.info("analysisInfo, time_begin2:%d, time_end2:%d" % (time_begin2, time_end2))

    logging.info("analysisInfo, daliy_open_user1:%d, daliy_paid_money1:%d" % (daliy_open_user1, daliy_paid_money1))
    logging.info("analysisInfo, daliy_open_user2:%d, daliy_paid_money2:%d" % (daliy_open_user2, daliy_paid_money2))

    arpu1 = 0
    if daliy_open_user1 > 0:
        arpu1 = daliy_paid_money1 / daliy_open_user1
    arpu2 = 0
    if daliy_open_user2 > 0:
        arpu2 = daliy_paid_money2 / daliy_open_user2

    arpu_rate = 0
    if arpu2 > 0:
        arpu_rate = (arpu2-arpu1)*100/arpu2
    strResult = "cur_user:%d, cur_money:%d, yesterday_arpu:%.01f, cur_arpu:%.01f, rate:%.01f%%" % (daliy_open_user, daliy_paid_money, arpu1, arpu2, arpu_rate)
    logging.info("analysisInfo, %s" % (strResult))
    #发邮件通知
    ktlib.send_email("admin@sky-mobi.com", "neo.chen@sky-mobi.com", "mopo arpu test", strResult)
    ktlib.send_email("admin@sky-mobi.com", "dub.chen@sky-mobi.com", "mopo arpu test", strResult)
    ktlib.send_email("admin@sky-mobi.com", "human.hu@sky-mobi.com", "mopo arpu test", strResult)
    ktlib.send_email("admin@sky-mobi.com", "tristan.yang@sky-mobi.com", "mopo arpu test", strResult)

#检查数据
def check_mopo():
    #http://open.mopo.com/media/appTodayData?appid=6000583
    try:
        conn = http.client.HTTPConnection("open.mopo.com")
        conn.request("GET", "/media/appTodayData?appid=6000583")
        r1 = conn.getresponse()
        print(r1.status, r1.reason)
        print(r1)
        data = r1.read()
        roominfo = bytes.decode(data)
        logging.info("check_mopo, info:%s" % (roominfo))
        #
        #格式
        #[{"appid":6000583,"day_key":"2013-07-08","daliy_open_user":826,"daliy_paid_money":167900}]
        #
        locations = json.loads(roominfo)
        for location in locations:
            appid = location["appid"]
            day_key = location["day_key"]
            daliy_open_user = location["daliy_open_user"]
            daliy_paid_money = location["daliy_paid_money"]
            #保存数据
            saveInfo(appid, day_key, daliy_open_user, daliy_paid_money)
            #分析数据
            analysisInfo(appid, day_key, daliy_open_user, daliy_paid_money)
    except:
        print("connect error")

def main():
    print("main start...")
    logging.basicConfig(level=logging.DEBUG,
                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                filename='%s.log' % (getAppName()),
                filemode='w')
    while True:
        logging.info("main, app check...")
        check_mopo()
        logging.info("main, app check end")
        time.sleep(get_check_inteval())

if __name__ == '__main__':
    ktlib.ForkMySelf(getAppName(), 3)
    try:
        main()
    except:
        ktlib.write_crash_log()
